%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%     Principal Component Estimator    %%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [fx,lx,ix,vnt] = pce(x,k)

[t,n] = size(x);

if k~=0; 
    if t > n; [fx,lx,ix,vnt]=pcn(x,k);
    else [fx,lx,ix,vnt]=pct(x,k); end
else ix = x; fx = []; lx = []; vnt = [];
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% TxT Principal Components
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [f,l,e,vnt] = pct(x,k)

[t,n] = size(x);
x = x - repmat(mean(x),t,1);
vx = x*x';
[ve, va, ve1] = svd(vx);

if k~=0; ve = ve(:,1:k);
         f = ve.*sqrt(t);
         l = x'*f/t;
         e = x-f*l';
         vnt = va(1:k,1:k);
else e = x; 
     f = zeros(t,1);
     l = zeros(n,1);
     vnt = 0;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% NxN Principal Components
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [f,l,e,vnt] = pcn(x,k)

[t,n] = size(x);
x = x - repmat(mean(x),t,1);
vx = x*x';
[ve, va, ve1] = svd(vx);

if k~=0; ve = ve(:,1:k);
         f = ve.*sqrt(n);
         l = x'*f/n;
         e = x-f*l';
         vnt = va(1:k,1:k);
else e = x; 
     f = zeros(t,1);
     l = zeros(n,1);
     vnt = 0;
end
